#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#define MAX 1024
#define ARGC 64
#include<assert.h>
#define SEP " "
#include<stdlib.h>
#include<sys/wait.h>
int split(char* commendStr,char*argv[])
{
   assert(commendStr);
   assert(argv);
   argv[0]=strtok(commendStr,SEP);
   if(argv[0]==NULL) return -1;
   int i=1;
   while(argv[i++]=strtok(NULL,SEP))
   {}
   return 0; 
}

int main()
{
   while(1)
   {
     int last_exit=0; 
     char commendStr[MAX]={0};
      char *argv[ARGC]={NULL};
      printf("[User@VM-4-8-centos5 ~]# ");
      fflush(stdout);
      char*ret=fgets(commendStr, sizeof(commendStr),stdin);
      assert(ret);
      (void)ret;
      commendStr[strlen(commendStr)-1]='\0';
     int n = split(commendStr,argv);
     if(n!=0)
       continue;
     if(strcmp(argv[0],"cd")==0)
     {
       if(argv[1]!=NULL)
         chdir(argv[1]);
       continue;
     }
     if(strcmp(argv[0],"ls")==0)
     {
       int pos = 0;
       while(argv[pos]) pos++;
       argv[pos++] = (char*)"--color=auto";
       argv[pos] = NULL; // 比较安全的做法
     }
     if(strcmp(argv[0],"ll")==0)
     {
       argv[0]="ls";
       argv[1]="-l";
       argv[2]="--color=auto";
     }
     pid_t id=fork();

     if(id==0)
     {
       //调用子进程
       execvp(argv[0],argv);
       exit(1);
     }
     int statue=0;
    pid_t ret_id=wait(&statue);
     if(ret_id>0)
     {
       last_exit=WEXITSTATUS(statue);
     }
   }
}
